// Load data

clear
import excel data_reflection_horp.xlsx, sheet("Data") firstrow


// Uncomment line below to perform analysis for original data only
//drop if session >= 12


// Aggregate data by subject for each treatment and risk order

forval i= 2/4 {
	foreach treat in "loss" "gain" "sprg" {
		quietly egen `treat'`i' = rowtotal(`treat'`i'_*) if `treat'2_a ~= .
	}
}


// Binomial tests

foreach treat in "loss" "gain" "sprg" {
	forval i= 2/4 {
		quietly sum(`treat'`i')
		bitesti r(N)*12 r(sum) 0.5
	}
}

// Wilcoxon signed rank tests

forval i= 2/4 {
	foreach gaintreat in "gain" "sprg" {
		signrank loss`i' = `gaintreat'`i'
	}
}


// Spearman correlations between order and consistency

quietly reshape long loss gain sprg, i(id) j(order)

foreach treat in "loss" "gain" "sprg" {	
	quietly gen `treat'_consistency = abs(`treat' - 6)
	spearman order `treat'_consistency
}


// Calculate average consistencies and perform Mann-Whiney U test

forval i= 2/4 {
	foreach gaintreat in "gain" "sprg" {
		sum `gaintreat'_consistency if order == `i'
	}
}

quietly drop loss_consistency
quietly reshape wide loss gain sprg gain_consistency sprg_consistency, i(id) j(order)

forval i= 2/4 {
	quietly rename gain_consistency`i' g_consistency`i'_1
	quietly rename sprg_consistency`i' g_consistency`i'_2
}

quietly reshape long g_consistency2_ g_consistency3_ g_consistency4_, i(id) j(gain_treat)

forval i= 2/4 {
	ranksum g_consistency`i'_, by(gain_treat)
}

quietly reshape wide g_consistency2_ g_consistency3_ g_consistency4_, i(id) j(gain_treat)


// Calculate average response by task

forval i= 2/4 {
	foreach treat in "loss" "gain" "sprg" {
		mean `treat'`i'_*
	}
}


// Spearman rank correlations

foreach treat in "loss" "gain" "sprg" {
	spearman `treat'2 `treat'3 `treat'4, stats(rho p)
}


// Fisher's exact tests

foreach treat in "loss" "gain" "sprg" {
	quietly gen `treat'2_type = "Risk averse" if `treat'2 >= 10
	quietly replace `treat'2_type = "Risk loving" if `treat'2 <= 2
	quietly replace `treat'2_type = "Risk neutral" if `treat'2 > 2 & `treat'2 < 10
	quietly replace `treat'2_type = "." if `treat'2 == .
}

foreach treat in "loss" "gain" "sprg" {
	quietly gen `treat'4_type = "Temperate" if `treat'4 >= 10
	quietly replace `treat'4_type = "Intemperate" if `treat'4 <= 2
	quietly replace `treat'4_type = "Temperance neutral" if `treat'4 > 2 & `treat'4 < 10
	quietly replace `treat'4_type = "." if `treat'4 == .
}

foreach treat in "loss" "gain" "sprg" {
	tabulate `treat'2_type `treat'4_type, exact, if `treat'2_type ~= "."
}

tabulate sprg2_type sprg4_type, exact, if sprg2_type ~= "." & sprg2_type ~= "Risk neutral" & sprg4_type ~= "Temperance neutral"
